package com.example.plugin.activity;


import java.io.File;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import com.example.host.R;
import com.example.plugin.PluginManager;
import com.example.plugin.parser.PluginPackageParser;

public class MainActivity extends Activity {

	private File mRoot;
	private Button mBtn;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		mRoot = getExternalFilesDir("plugin");
		if (!mRoot.exists() && !mRoot.mkdirs()) {
			throw new IllegalStateException("plugin dir invalid");
		}
		
		try {
			scanAllPlugins();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		mBtn = (Button) findViewById(R.id.btn);
		mBtn.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				launchApk("com.example.plugin");
			}
		});
	}
	
	private void scanAllPlugins() throws Exception {
		File[] files = mRoot.listFiles();
		if (files != null) {
			for (File file : files) {
				PluginManager.installPlugin(this, file);
			}
		}
	}
	
	private void launchApk(String packageName) {
		ComponentName component = PluginManager.getLauncherComponent(packageName);
		
		Intent intent = new Intent();
		intent.setClassName(component.getPackageName(), component.getClassName());
		startActivity(intent);
	}
}
